<template>
<div class="field-list__wrapper">
  <div class="field-list__empty" v-if="!hasFields">
    <img src="../../../../../assets/img/configBusiness/fields-empty@2x.png" alt="">
    <div class="empty-title">{{$t('configLazyLoad.businessConfig.fieldTip1')}}<br>{{$t('configLazyLoad.businessConfig.fieldTip2')}} </div>
    <el-button class="primary_btn"
               plain
               type="primary"
               @click.stop="addField"
               size="mini">
      <i class="el-icon-plus"></i>{{$t('configLazyLoad.businessConfig.addFields')}}</el-button>
  </div>
  <!--翻页组件（真翻页）-->
  <table-box @turnPage="search" :pagination="pagination" v-if="hasFields">
    <div slot="search" class="fl">
      <el-button type="text"
                 class="primary_btn"
                 @click.stop="addField"
                 size="mini">
        <i class="el-icon-plus"></i>{{$t('configLazyLoad.businessConfig.addFields')}}</el-button>
      <el-input
        size="mini"
        :placeholder="$t('configLazyLoad.businessConfig.fieldsPlaceholder')"
        v-model="name"
        @keyup.enter.native="search"
        style="width:210px"
      >
        <i
          class="el-input__icon el-icon-search"
          slot="suffix"
          @click.stop="search">
        </i>
      </el-input>
    </div>
    <el-table
      slot="table"
      size="mini"
      :stripe="true"
      slot-scope="slotScope"
      :data="fieldList">
      <template v-for="item in tableHead">
        <el-table-column
          :prop="item.prop"
          :label="item.label"
        >
          <template scope="scope" >
            <!--文字样式有变化-->
            <span v-if="item.prop === 'status'" :class="['field-table__' + scope.row.enable]">{{scope.row.enable === 'yes' ? $t('configLazyLoad.public.reuse'): $t('public.disabled')}}</span>
            <!--操作-->
            <template v-else-if="item.prop === 'operate'">
              <span class="field-table__button" @click="detail(scope.row)">{{$t('public.edit')}}</span>
              <el-popover
                placement="top"
                v-model="scope.row.showPopover"
                trigger="click">
                <div class="popover"><i class="field-table__no el-icon-warning"></i>{{$t('configLazyLoad.businessConfig.fieldTip3')}}{{scope.row.enable !== 'yes' ? $t('configLazyLoad.public.reuse'): $t('configLazyLoad.public.stop')}}{{$t('configLazyLoad.businessConfig.fieldTip4')}}</div>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" @click="changeStatus(scope.row)">{{scope.row.enable !== 'yes' ? $t('configLazyLoad.public.reuse'): $t('configLazyLoad.public.stop')}}</el-button>
                  <el-button type="primary" size="mini" @click="scope.row.showPopover = false">{{$t('public.cancel')}}</el-button>
                </div>
                <span :class="['field-table__button', 'field-table__' + scope.row.enable + '1']" slot="reference">{{scope.row.enable !== 'yes' ? $t('configLazyLoad.public.reuse'): $t('configLazyLoad.public.stop')}}</span>
              </el-popover>
            </template>
            <template v-else-if="item.prop === 'updateTimeArr'">
              <el-popover
                :disabled="!scope.row.updateTimeArr.length"
                placement="right"
                v-model="scope.row.showUpdateTime"
                trigger="click">
                <span slot="reference" class="update-time">{{scope.row.updateTimeArr[0]}}</span>
                <div class="update-time-content">
                  {{$t('configLazyLoad.businessConfig.editHistory')}}
                  <br>
                  <template v-for="time in scope.row[item.prop]" >
                    {{time}}<br>
                  </template>
                </div>
              </el-popover>
            </template>
            <!--普通-->
            <template v-else>{{scope.row[item.prop]}}</template>
          </template>
        </el-table-column>
      </template>
    </el-table>
  </table-box>
  <!--右侧滑出框-->
  <right-layout :visible="dialogObj.visible"
                :title="dialogObj.title"
                @close="dialogObj.visible = false"
                @save="save"
                >
    <!--添加，编辑字段-->
    <field-info ref="fieldInfo" :custFieldsList="custFieldsList">
    </field-info>
  </right-layout>
</div>
</template>

<script>
  import rightLayout from '../base/rightLayout'
  import tableBox from '../base/tableBox'
  import fieldInfo from './fieldInfo'
  import {deepClone, getCurrentDateTime} from '@/utils/m7Utils'
  export default {
    name: 'fields-config',
    data () {
      return {
        pagination: {
          currentPage: 0,
          count: 0
        },
        name: '',
        tableHead: [
          {prop: 'name', label: this.$t('configLazyLoad.questionnaireConfig.fieldName')},
          {prop: 'typeName', label: this.$t('configLazyLoad.businessConfig.fieldsType')},
          {prop: 'status', label: this.$t('public.state')},
          {prop: 'createTime', label: this.$t('public.createTime')},
          {prop: 'updateTimeArr', label: this.$t('configLazyLoad.businessConfig.editTime')},
          {prop: 'operate', label: this.$t('public.operate')}
        ],
        fieldList: [],
        dialogObj: {
          visible: false,
          title: this.$t('configLazyLoad.businessConfig.newField'),
          type: 'add'
        },
        custFieldsList: [],
        currentField: {}
      }
    },
    inject: ['busType'],
    components: {
      rightLayout,
      tableBox,
      fieldInfo
    },
    computed: {
      flowId () {
        let flowInfo = this.$store.state.config.businessConfig[this.busType].flowInfo || {}
        return flowInfo._id
      },
      hasFields () {
        let config = this.$store.state.config.businessConfig[this.busType] || {}
        return config.allFields && config.allFields.length
      }
    },
    methods: {
      initData () {
        this.name = ''
        this.search(1)
        this.$store.dispatch('getCustomerTemplate', {account: this.$store.state.session.user.account}).then((res) => {
          if (res.success) {
            let custTmpl = res.data[0]
            this.custFieldsList = [{label: this.$t('configLazyLoad.businessConfig.notAssociated'), value: 'no'}]
            console.log(res)
            if (custTmpl) {
              let stableFields = custTmpl.stable_fields || []
              stableFields.forEach((item) => {
                // 省市县算一个字段
                if (item.name !== 'province' && item.name !== 'city' && item.name !== 'district') {
                  this.custFieldsList.push({label: item.value, value: 'stable_' + item.name, type: 'single'})
                } else if (item.name === 'province') {
                  this.custFieldsList.push({label: '省市县', value: 'stable_' + item.name, type: 'dropdown'})
                }
              })
              let customFields = custTmpl.custom_fields || []
              customFields.forEach((item) => {
                if (item.status === 'stop') {
                  return
                }
                // 字典id，导出工单时使用
                let dicId = item.dic && item.dic.isDic && item.dic.dicId || ''
                this.custFieldsList.push({label: item.name, value: 'custom_' + item._id, type: item.type, dicId})
              })
            }
          }
        })
      },
      turnPage (val) {
      },
      /*
      * 字段编辑
      */
      detail (data) {
        this.dialogObj.visible = true
        this.dialogObj.title = this.$t('configLazyLoad.businessConfig.editFields')
        this.dialogObj.type = 'edit'
        this.currentField = data
        this.$refs.fieldInfo.initData('edit', data)
      },
      addField () {
        this.dialogObj.visible = true
        this.dialogObj.title = this.$t('configLazyLoad.businessConfig.newField')
        this.dialogObj.type = 'add'
        this.currentField = {}
        this.$refs.fieldInfo.initData('add')
      },
      save () {
        let data = this.$refs.fieldInfo.create()
        if (!data.success) {
          return
        }
        if (this.dialogObj.type === 'edit' && data.isChange) {
          this.$confirm(this.$t('configLazyLoad.businessConfig.fieldTip5'), this.$t('configLazyLoad.businessConfig.fieldTip6'), {
            confirmButtonText: this.$t('public.confirm'),
            cancelButtonText: this.$t('public.cancel'),
            type: 'warning'
          }).then(() => {
            let form = deepClone(data.data)
            // null 改为 ''
            for (let i in form) {
              if (!form[i]) {
                form[i] = ''
              }
            }
            form.flow_id = this.flowId
            if (this.dialogObj.type === 'edit') {
              // 编辑
              form._id = this.currentField._id
            }
            this.$store.dispatch('addBusinessFlowFields', form).then((res) => {
              if (res.success) {
                this.dialogObj.visible = false
                let searchPage = 1
                if (this.dialogObj.type === 'edit') {
                  // 编辑
                  searchPage = this.pagination.currentPage
                }
                this.search(searchPage)
                // 编辑
                if (form._id) {
                  this.$store.commit('flowConfig/UPDATE_FLOW_FIELD', {type: 'update', data: form})
                } else {
                  // 添加
                  this.$store.commit('flowConfig/UPDATE_FLOW_FIELD', {type: 'add', data: res.newData})
                }
              }
            })
          }).catch(() => {
                   
          })
        } else {
          let form = deepClone(data.data)
          // null 改为 ''
          for (let i in form) {
            if (!form[i]) {
              form[i] = ''
            }
          }
          form.flow_id = this.flowId
          if (this.dialogObj.type === 'edit') {
            // 编辑
            form._id = this.currentField._id
          }
          this.$store.dispatch('addBusinessFlowFields', form).then((res) => {
            if (res.success) {
              this.dialogObj.visible = false
              let searchPage = 1
              if (this.dialogObj.type === 'edit') {
                // 编辑
                searchPage = this.pagination.currentPage
              }
              this.search(searchPage)
              // 编辑
              if (form._id) {
                this.$store.commit('flowConfig/UPDATE_FLOW_FIELD', {type: 'update', data: form})
              } else {
                // 添加
                this.$store.commit('flowConfig/UPDATE_FLOW_FIELD', {type: 'add', data: res.newData})
              }
            }
          })
        }
      },
      /*
      * 字段查询
      * */
      search (val) {
        let page = typeof val === 'number' ? val : 1
        let p1 = this.$store.dispatch('getCache', {type: 'businessFieldType'})
        let p2 = this.$store.dispatch('queryBusinessFlowFields', {page, flow_id: this.flowId, query: this.name, limit: 10})
        Promise.all([p1, p2]).then(([res1, res2]) => {
          res2.list.forEach((item) => {
            // popover弹框的显示隐藏
            (res1 || []).some((one) => {
              if (one.code_value === item.type) {
                item.typeName = one.code_name
              }
            })
            item.showPopover = false
            item.showUpdateTime = false
            item.updateTimeArr = (item.updateTimeArr || []).map((item) => {
              return item.updateTime || ''
            })
          })
          this.pagination.currentPage = page
          this.pagination.count = res2.count
          this.fieldList = res2.list
        })
      },
      /*
      * 字段启用停用
      * */
      changeStatus (data) {
        let form = deepClone(data)
        delete form.typeName
        delete form.showPopover
        delete form.updateTimeArr
        delete form.showUpdateTime
        form.enable = form.enable === 'yes' ? 'no' : 'yes'
        this.$store.dispatch('addBusinessFlowFields', form).then((res) => {
          if (res.success) {
            this.fieldList.forEach((item) => {
              if (item._id === data._id) {
                item.enable = form.enable
                item.showPopover = false
                item.updateTimeArr.unshift(getCurrentDateTime())
              }
            })
            this.$store.commit('flowConfig/UPDATE_FLOW_FIELD', {type: 'update', data: form})
          }
        })
      }
    }
  }
</script>

<style scoped lang='stylus'>
  @import '../../../../../assets/common.styl'
  .field-list__wrapper
    height 100%
    overflow-y auto
    box-sizing border-box
    padding 20px
  .field-list__empty
    padding-top 60px
    text-align center
    img
      width 173px
      height 173px
    .empty-title
      padding 10px 0
      color $cf-gray5
  .field-table__button
    color $c-main
    display inline-block
    padding-right:10px
    cursor pointer
  .field-table__no
    color $cf-color0
  .field-table__yes1
    color $c-pink
  .popover
    font-size 12px
    padding-bottom 15px
    i
      font-size 16px
      margin-right 5px
  .update-time
    &:hover
      cursor pointer
      color $c-main
  .update-time-content
    font-size 12px
    max-height 350px
    overflow-y auto
</style>
